﻿using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using CRM.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;

namespace CRM.Caches
{
    public class UserCache : BaseCache<User>
    {

        public UserCache(IMemoryCache cache) : base(cache)
        {
        }
        
        public Task<User> GetOrCreateAsync(MyDbContext dbContext,UserManager<User> userManager, ClaimsPrincipal claimsPrincipal)
        {
            var id = userManager.GetUserId(claimsPrincipal);
            return GetOrCreateAsync(id, entry =>
            {
                entry.SlidingExpiration = TimeSpan.FromMinutes(1);
                return GetItem(id, dbContext);
            });
        }

        /// <summary>
        /// 获取用户缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="dbContext"></param>
        /// <returns></returns>
        protected override Task<User> GetItem(object key, MyDbContext dbContext)
        {
            var userId = Convert.ToInt32(key);
            return dbContext.Users.Where(m => m.Id == Convert.ToInt32(userId)).Include(m => m.Company).FirstOrDefaultAsync();
        }
        
        /// <summary>
        /// 清除用户缓存
        /// </summary>
        /// <param name="userManager"></param>
        /// <param name="principal"></param>
        public void FlushItem(UserManager<User> userManager, ClaimsPrincipal principal)
        {
            var userId = userManager.GetUserId(principal);
            FlushItem(userId);
        }
    }
}